/*
 * Copyright 2008. Mount Sinai Hospital, Toronto, Canada.
 * 
 * Licensed under the Apache License, Version 2.0. You
 * can find a copy of the license at:
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * IN NO EVENT SHALL MOUNT SINAI HOSPITAL BE LIABLE TO ANY PARTY FOR DIRECT, 
 * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST 
 * PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, 
 * EVEN IF MOUNT SINAI HOSPITAL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
 * DAMAGE.
 * 
 * MOUNT SINAI HOSPITAL SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND 
 * ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". 
 * MOUNT SINAI HOSPITAL HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, 
 * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 
 */

package com.sinai.mshab.extensions.search;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * This class stores the structure of the database.
 * 
 * @author serge
 * 
 */
public class DatabaseStructure {

	private ArrayList<Field> tables = new ArrayList<Field>();
	private HashMap<String, ArrayList<Field>> tableToFields = new HashMap<String, ArrayList<Field>>();

	public DatabaseStructure() {

	}

	/**
	 * Returns the table names.
	 * 
	 * @param table
	 *            the table name for which to retrieve
	 * @return
	 */
	public ArrayList<String> getTableNames() {
		return new ArrayList<String>(tableToFields.keySet());
	}

	/**
	 * Returns the fields of a give table
	 * 
	 * @param table
	 *            the table for which to return the fields
	 * @return Returns the fields of a give table
	 */
	public ArrayList<Field> getFields(String table) {
		return tableToFields.get(table);
	}

	/**
	 * Returns the type given a table name and a column name
	 * 
	 * @param table
	 *            the table the column belongs to
	 * @param field_name
	 *            the name of the column
	 * @return
	 */
	public String getType(String table, String field_name) {
		ArrayList<Field> fields = getFields(table);
		for (int i = 0; i < fields.size(); i++) {
			Field current = fields.get(i);
			if (current.getName().equals(field_name)) {
				return current.getType();
			}
		}
		return "";
	}

	/**
	 * Add a table to the structure
	 * 
	 * @param table
	 *            the table to add
	 */
	public void addTable(String table) {
		if (!tableToFields.containsKey(table)) {
			tableToFields.put(table, new ArrayList<Field>());
		}
	}

	/**
	 * Add a field to the database structure
	 * 
	 * @param table
	 *            the table to which the field belongs
	 * @param field
	 *            the new field to be added.
	 */
	public void addField(String table, Field field) {

		// check if the table exists
		if (!tableToFields.containsKey(table)) {
			addTable(table);
		}

		ArrayList<Field> fields = tableToFields.get(table);
		fields.add(field);
	}
}
